import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Injectable } from '@angular/core';

import { Platform } from '@ionic/angular';

import { AppVersion } from '@ionic-native/app-version/ngx';

import { EventService } from '../../shared/service/event.service';

import { AppGlobalService } from './app-global.service';
declare let wx;
declare let BMap;
declare let cordova;
declare let BMAP_STATUS_SUCCESS;
@Injectable({
    providedIn: 'root'
})
export class MapBaiduService {
    constructor(
        private eventService: EventService,
        private platform: Platform,
        private appVersion: AppVersion,
        private appGlobalService: AppGlobalService,
        private pageModalService: PageModalService) {

        this.eventService.eventEmit.on('getPointByName', res => {
            const positionInfo = JSON.parse(res);
            // 通过城市名称设置经纬度
            this.getPointByName(positionInfo.name, (point) => {
                positionInfo.center = { lng: point.lng, lat: point.lat };
                localStorage.setItem('position', JSON.stringify(positionInfo));
            });
        });
        this.eventService.eventEmit.on('getAddressByPoint', res => {
            const pointArray = res.split(',');
            this.refreshLocationStore(pointArray[0], pointArray[1], (res) => {
                console.log('getAddressByPoint='+pointArray[0]+', '+pointArray[1]+'=', res.poisDetail);
                this.appGlobalService.callBackFunctionOnGetAddressByPoint = res.poisDetail;
            });

        });
    }

    localCityName: string;
    headers: any;
    lat: any;
    long: any;
    // locationObj = { center: { lng: 114.066112, lat: 22.548511 }, name: '北京', code: '1101' };
    // defaultCityId = 1101; // 1101;
    // defaultCityName = '北京'; // '北京';
    locationObj = {
        center: { lng: 114.066112, lat: 22.548511 }, name: '深圳', code: '4403', district: '', districtCode: '440304',
        locationDescribe: ''
    };
    defaultCityId = 4403; // 1101;
    defaultCityName = '深圳'; // '北京';
    // tslint:disable-next-line:max-line-length
    c2 = [33, 6202, 34, 6203, 35, 6204, 36, 6201, 37, 6209, 38, 2327, 39, 2311, 40, 2307, 41, 2302, 42, 2308, 43, 2304, 44, 2312, 45, 2305, 46, 2303, 47, 2309, 48, 2301, 49, 2310, 50, 2306, 51, 2208, 52, 2207, 53, 2201, 54, 2224, 55, 2202, 56, 2203, 57, 2206, 58, 2101, 59, 2109, 60, 2112, 61, 1507, 62, 1522, 63, 1525, 64, 1505, 65, 6328, 66, 6301, 67, 6322, 68, 6325, 69, 6321, 70, 6323, 71, 6327, 72, 6326, 73, 5133, 74, 5106, 75, 5101, 76, 5118, 77, 5114, 78, 5103, 79, 5111, 80, 5134, 81, 5104, 82, 6532, 83, 6531, 84, 6530, 85, 6529, 86, 6528, 88, 6527, 89, 6521, 90, 6540, 91, 6522, 92, 6501, 93, 6523, 94, 6542, 95, 6502, 96, 6543, 97, 5422, 98, 5426, 99, 5421];
    // tslint:disable-next-line:max-line-length
    c3 = [100, 5401, 101, 5424, 102, 5423, 103, 5425, 104, 5301, 105, 5323, 106, 5304, 107, 5325, 108, 5308, 109, 5328, 110, 5309, 111, 5329, 112, 5305, 113, 5333, 114, 5307, 115, 5334, 116, 5331, 117, 6207, 118, 6206, 119, 4419, 121, 4602, 122, 4207, 123, 1503, 124, 3712, 125, 4601, 126, 3403, 127, 3401, 128, 3412, 129, 3402, 130, 3408, 131, 3408, 132, 5001, 133, 3507, 134, 3505, 135, 6210, 136, 6211, 137, 4402, 138, 4406, 139, 4409, 140, 4404, 141, 4414, 142, 4503, 143, 4512, 144, 4514, 145, 4507, 146, 5201, 147, 5202, 148, 1303, 149, 1309, 150, 1301, 151, 1304, 152, 4107, 153, 4103, 154, 4114, 155, 4110, 156, 4206, 157, 4210, 158, 4301, 159, 4304, 160, 3211, 161, 3206, 162, 3208, 163, 3601, 164, 3605, 165, 2205, 166, 2107, 167, 2102, 168, 1509, 169, 1508, 170, 6105, 171, 6103, 172, 3704, 173, 3711, 174, 3705, 175, 3710, 176, 1401, 177, 5326, 178, 3303, 179, 3301, 180, 3302, 181, 6405, 182, 6229, 183, 2204, 184, 2104, 185, 5132, 186, 5115, 187, 4420, 188, 3416, 189, 3411, 190, 3418, 191, 1310, 192, 3509, 193, 3508, 194, 3502, 195, 3503, 196, 6205, 197, 4418, 198, 4408, 199, 4417, 200, 4416, 201, 4451, 202, 4513, 203, 4510, 204, 4506, 205, 5222, 206, 5224, 207, 1308, 208, 1311, 209, 4109, 210, 4102, 211, 4108, 212, 4112, 213, 4104, 214, 4115, 215, 4106, 216, 4203, 217, 4208, 218, 4201, 219, 4307, 220, 4306, 221, 4313, 222, 4302, 223, 3209, 224, 3205, 225, 3602, 226, 3610, 227, 2105, 228, 2111, 229, 1502, 230, 1529, 231, 6108, 232, 6102, 233, 6101, 234, 3713, 235, 3716, 236, 3702, 237, 1406, 238, 1407, 239, 5119, 240, 5107, 241, 5116, 242, 5120, 243, 3308, 244, 3310, 245, 3309, 246, 6404, 247, 6230, 248, 5110, 249, 5303, 250, 3404, 251, 3414, 252, 3410, 253, 3406, 254, 3504, 255, 3506, 256, 6212, 257, 4401, 258, 4453, 259, 4452, 260, 4511, 261, 4501, 262, 5203, 263, 5204, 264, 1307, 265, 1302, 266, 1305, 267, 4105, 268, 4101, 269, 4117, 270, 4205, 271, 4211, 272, 4309, 273, 4305, 274, 4331, 275, 4310, 276, 3212, 277, 3213, 278, 3609, 279, 3606, 280, 2113, 281, 2108, 282, 2106, 283, 1506, 284, 6106, 285, 6110, 286, 3708, 287, 3707, 288, 3701, 289, 3101, 290, 1405, 291, 5113, 292, 3311, 293, 3306, 294, 3305, 295, 4505, 297, 1504, 298, 3415, 299, 3417, 300, 3501, 301, 4413, 302, 4407, 303, 4405, 304, 4504, 305, 4502, 306, 5227, 307, 1306, 308, 4116, 309, 4113, 310, 4209, 311, 4202, 312, 4308, 313, 4303, 314, 4311, 315, 3201, 316, 3203, 317, 3202, 318, 3608, 319, 2114, 320, 2103, 321, 1501, 322, 6403, 323, 6104, 324, 6109, 325, 3709, 326, 3706, 327, 1411, 328, 1408, 329, 5108, 330, 5109, 331, 5105, 332, 1201, 333, 3307, 334, 3304, 335, 6402, 336, 5306, 337, 3407, 338, 4412, 339, 4415, 340, 4403, 341, 4508, 342, 5226, 343, 5223, 344, 4111, 346, 3210, 347, 3207, 348, 3204, 349, 3604, 350, 3603, 351, 2110, 352, 6107, 353, 3717, 354, 3703, 355, 1402, 356, 1404, 357, 1403, 358, 3405, 359, 6208, 360, 6401, 361, 4509, 362, 4212, 363, 4312, 364, 3611, 365, 3607, 366, 3715, 367, 1409, 368, 1410, 369, 5117, 370, 3413, 371, 4213, 372, 3714, 373, 4228];
    c4 = [2911, 8201, 2912, 8101, 9002, 7101, 9004, 7106, 9016, 7105, 9017, 7103, 9019, 7102];



    // tslint:disable-next-line:ban-types
    ionViewDidLoad(callbackFunc?: Function) {
        const that = this;
        const myCity = new BMap.LocalCity();
        myCity.get((result) => {
            // tslint:disable-next-line:max-line-length
            if (result.code === 1) { result.code = 4403; result.name = "深圳"; } else { result.name = String(result.name).replace("市", ""); result.code = this.getCityId(result.code); }
            that.setStore('currentCityPosition', result);
            that.setStore('position', result);
            callbackFunc();
        });
    }
    // tslint:disable-next-line:max-line-length
    getCityId(code) { let id = 4403; if (code >= 100) { for (let i = 0; i < this.c3.length; i++) { if (code === this.c3[i]) { id = this.c3[i + 1]; break; } } } else if (code <= 99) { for (let i = 0; i < this.c2.length; i++) { if (code === this.c2[i]) { id = this.c2[i + 1]; break; } } } else { for (let i = 0; i < this.c4.length; i++) { if (code === this.c4[i]) { id = this.c4[i + 1]; break; } } } return id; }

    getPointByCityName(cityName, districtName?) {
        const that = this;
        const myGeo = new BMap.Geocoder();
        try {
            let isReturn = false;
            // 预防第三方的getPoint没有任何返回导致取不到值
            setTimeout(() => {
                console.log('msg----->2.5s later=' + isReturn);
                if (!isReturn) {
                    localStorage.setItem('tempPoint', JSON.stringify(this.appGlobalService.defaultCityCenter));
                    that.eventService.eventEmit.emit('storePoint', '临时存储经纬度信息');
                }
            }, 2500);
            myGeo.getPoint((districtName !== undefined ? cityName + districtName : cityName), (point) => {
                if (point) {
                    isReturn = true;
                    localStorage.setItem('tempPoint', JSON.stringify(point));
                    that.eventService.eventEmit.emit('storePoint', '临时存储经纬度信息');
                }
            }, cityName);
        } catch (error) {
            console.log('error----->' + JSON.stringify(error));
            localStorage.setItem('tempPoint', JSON.stringify(this.appGlobalService.defaultCityCenter));
            that.eventService.eventEmit.emit('storePoint', '临时存储经纬度信息');
        }

    }

    // tslint:disable-next-line:ban-types
    getPointByName(cityName, callbackFunc: Function) {
        let center = {};
        let isMatch = false;
        // tslint:disable-next-line:max-line-length
        const data = [{ i: 1101, n: "北京", center: { lng: 116.73139399850756, lat: 39.91043315891319 } }, { i: 6103, n: "宝鸡", center: { lng: 107.37544482560044, lat: 34.356307850276906 } }, { i: 5001, n: "重庆", center: { lng: 106.58032307590051, lat: 29.612548851859376 } }, { i: 5101, n: "成都", center: { lng: 104.07274197405957, lat: 30.578983930260147 } }, { i: 2201, n: "长春", center: { lng: 125.33025299438572, lat: 43.82279514129793 } }, { i: 4301, n: "长沙", center: { lng: 112.94535848173929, lat: 28.23445086024441 } }, { i: 3204, n: "常州", center: { lng: 119.98056278233405, lat: 31.817431532606935 } }, { i: 2102, n: "大连", center: { lng: 121.62131402342563, lat: 38.91965812675174 } }, { i: 4419, n: "东莞", center: { lng: 113.75818411369687, lat: 23.02731365008755 } }, { i: 4228, n: "恩施", center: { lng: 109.48612195693815, lat: 30.30079042387064 } }, { i: 4406, n: "佛山", center: { lng: 113.12826049029337, lat: 23.02721935806125 } }, { i: 3501, n: "福州", center: { lng: 119.310993865828, lat: 26.088859870746074 } }, { i: 3607, n: "赣州", center: { lng: 114.93997202527355, lat: 25.837286023548756 } }, { i: 5201, n: "贵阳", center: { lng: 106.634857855935, lat: 26.652434455997888 } }, { i: 4401, n: "广州", center: { lng: 113.25078136689486, lat: 23.131755907107397 } }, { i: 4503, n: "桂林", center: { lng: 110.18621742061988, lat: 25.241837684146706 } }, { i: 4413, n: "惠州", center: { lng: 114.4221522582896, lat: 23.117971870471518 } }, { i: 4601, n: "海口", center: { lng: 110.20668369470806, lat: 20.05212692367124 } }, { i: 2301, n: "哈尔滨", center: { lng: 126.54188296501971, lat: 45.80861027790872 } }, { i: 3301, n: "杭州", center: { lng: 120.2164809855364, lat: 30.25186303959434 } }, { i: 3401, n: "合肥", center: { lng: 117.23367379898433, lat: 31.826971533173275 } }, { i: 3604, n: "九江", center: { lng: 115.96012674852665, lat: 29.66709487202274 } }, { i: 3701, n: "济南", center: { lng: 117.53284384907748, lat: 36.6866245534709 } }, { i: 2202, n: "吉林", center: { lng: 126.55583994742496, lat: 43.843744424544546 } }, { i: 5301, n: "昆明", center: { lng: 102.84016843885692, lat: 24.88783293308645 } }, { i: 4103, n: "洛阳", center: { lng: 112.50997047647733, lat: 34.70287027627618 } }, { i: 4502, n: "柳州", center: { lng: 109.4349700025371, lat: 24.332413044765584 } }, { i: 3713, n: "临沂", center: { lng: 118.65722635590434, lat: 34.92599846654946 } }, { i: 6201, n: "兰州", center: { lng: 103.84075493542997, lat: 36.06674602245615 } }, { i: 5107, n: "绵阳", center: { lng: 104.5621610938722, lat: 32.41559434442762 } }, { i: 4409, n: "茂名", center: { lng: 110.92495782092193, lat: 21.64750222227161 } }, { i: 3201, n: "南京", center: { lng: 118.80332011658638, lat: 32.066627620756115 } }, { i: 4501, n: "南宁", center: { lng: 108.37295819507708, lat: 22.82380978321737 } }, { i: 3601, n: "南昌", center: { lng: 115.82307083962577, lat: 28.64345664335494 } }, { i: 3302, n: "宁波", center: { lng: 121.55308500778526, lat: 29.823889963663742 } }, { i: 3702, n: "青岛", center: { lng: 120.38910359436966, lat: 36.07300668847675 } }, { i: 3505, n: "泉州", center: { lng: 118.68188311908021, lat: 24.88123042461958 } }, { i: 3101, n: "上海", center: { lng: 121.48024807868293, lat: 31.236276016622966 } }, { i: 4112, n: "三门峡", center: { lng: 111.20749998026395, lat: 34.779228949498794 } }, { i: 4403, n: "深圳", center: { lng: 114.06450485520935, lat: 22.549179943799096 } }, { i: 1301, n: "石家庄", center: { lng: 114.52140317439488, lat: 38.04829153846363 } }, { i: 3205, n: "苏州", center: { lng: 120.59168154789141, lat: 31.305976454846554 } }, { i: 4602, n: "三亚", center: { lng: 109.51852687765616, lat: 18.258705649723847 } }, { i: 2101, n: "沈阳", center: { lng: 123.47112242619077, lat: 41.68365686333339 } }, { i: 1401, n: "太原", center: { lng: 112.55619700852913, lat: 37.876857010810696 } }, { i: 1201, n: "天津", center: { lng: 117.2080874529742, lat: 39.091091397203265 } }, { i: 4201, n: "武汉", center: { lng: 114.31175375989858, lat: 30.598604365240018 } }, { i: 3707, n: "潍坊", center: { lng: 119.1681603418337, lat: 36.71443859723835 } }, { i: 3303, n: "温州", center: { lng: 120.70576390527262, lat: 28.000064376976685 } }, { i: 3710, n: "威海", center: { lng: 122.12711886455412, lat: 37.51911603980767 } }, { i: 3402, n: "芜湖", center: { lng: 118.43946739858617, lat: 31.358947081937455 } }, { i: 3202, n: "无锡", center: { lng: 120.36430003178091, lat: 31.596036906305816 } }, { i: 6104, n: "咸阳", center: { lng: 108.71526632593539, lat: 34.3361665150197 } }, { i: 3203, n: "徐州", center: { lng: 117.29031321901617, lat: 34.20997355533047 } }, { i: 6101, n: "西安", center: { lng: 108.94616596574517, lat: 34.34938201363012 } }, { i: 3502, n: "厦门", center: { lng: 118.03945696942351, lat: 24.490422004233793 } }, { i: 4206, n: "襄阳", center: { lng: 112.16172437942417, lat: 32.0526558308794 } }, { i: 3706, n: "烟台", center: { lng: 121.40687996429153, lat: 37.547356027676194 } }, { i: 4205, n: "宜昌", center: { lng: 111.29362897357733, lat: 30.69832488940413 } }, { i: 4404, n: "珠海", center: { lng: 113.58353349040198, lat: 22.276826189572965 } }, { i: 4420, n: "中山", center: { lng: 113.39891571832442, lat: 22.5233339016208 } }, { i: 4302, n: "株洲", center: { lng: 113.13949757357508, lat: 27.834621242324275 } }, { i: 5203, n: "遵义", center: { lng: 107.0379320296565, lat: 27.728290001234935 } }, { i: 4101, n: "郑州", center: { lng: 113.683951844071, lat: 34.76026120810477 } }];
        // tslint:disable-next-line:prefer-for-of
        for (let i = 0; i < data.length; i++) {
            if (data[i].n === cityName) {
                center = data[i].center;
                isMatch = true;
                callbackFunc(center);
                break;
            }
        }
        if (!isMatch) {
            try {
                let isReturn = false;
                const myGeo = new BMap.Geocoder();
                setTimeout(() => {
                    console.log('msg----->2.5s later=' + isReturn);
                    if (!isReturn) {
                        callbackFunc(this.appGlobalService.defaultCityCenter);
                    }
                }, 2500);
                myGeo.getPoint(cityName, (point) => {
                    if (point) {
                        center = point;
                        isReturn = true;
                        callbackFunc(point);
                    }
                }, cityName);
            } catch (error) {
                callbackFunc(this.appGlobalService.defaultCityCenter);
            }
        }
    }

    refreshLocationStore(wxLng, wxLat, callFunction) {
        const that = this;
        let globalLng = 114.066112;
        let globalLat = 22.548511;
        if (wxLng) {
            globalLng = wxLng;
        }
        if (wxLat) {
            globalLat = wxLat;
        }
        const result = {
            center: { lng: globalLng, lat: globalLat },
            name: this.appGlobalService.defaultCityName,
            code: this.appGlobalService.defaultCityId,
            districtCode: this.appGlobalService.defaultDistrictCode,
            address: '',
            poisDetail: '',
            location: {}
        };
        try {
            const geoc = new BMap.Geocoder();
            const pt = new BMap.Point(result.center.lng, result.center.lat);
            geoc.getLocation(pt, rs => {
                try {
                    result.name = rs.addressComponents.city.replace('市', '');
                    result.code = this.getCityIdByName(result.name);
                    let poisLen = rs.surroundingPois.length - 1;
                    const poisDetail = rs.surroundingPois.length > 0 ? rs.surroundingPois[0].title : '';
                    result.address = rs.addressComponents.city
                        + poisDetail;
                    result.poisDetail = poisDetail;
                    // 返回同一个点则线上画矩形
                    if (poisLen === 0) {
                        // tslint:disable-next-line:max-line-length
                        rs.surroundingPois[1] = { point: { lng: rs.surroundingPois[0].point.lng + 0.05, lat: rs.surroundingPois[0].point.lat + 0.05 } };
                        poisLen = 1;
                    }
                    const begainLargeThanEnd = rs.surroundingPois[0].point.lat > rs.surroundingPois[poisLen].point.lat;
                    result.location = {
                        content: {
                            ll1: {
                                // tslint:disable-next-line:max-line-length
                                longitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lng : rs.surroundingPois[poisLen].point.lng,
                                // tslint:disable-next-line:max-line-length
                                latitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lat : rs.surroundingPois[poisLen].point.lat
                            },
                            ll2: {},
                            ll3: {},
                            ll4: {
                                // tslint:disable-next-line:max-line-length
                                longitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lng : rs.surroundingPois[0].point.lng,
                                // tslint:disable-next-line:max-line-length
                                latitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lat : rs.surroundingPois[0].point.lat
                            }
                        }
                    };
                } catch (error) {
                    console.log('msg----->get address error ' + JSON.stringify(error));
                } finally {
                    callFunction(result);
                }
            });
        } catch (error) {
            console.log('error----->' + JSON.stringify(error));
            callFunction(result);
        }
    }


    getStore(name: string) { if (!name) { return; } return window.localStorage.getItem(name); }
    setStore(name: string, content: any) {
        if (!name) { return; }
        if (typeof content !== 'string') { content = JSON.stringify(content); }
        window.localStorage.setItem(name, content);
    }
    removeStore(name: string) { if (!name) { return; } window.localStorage.removeItem(name); }

    // 获取指定中心点周围指定范围内的经纬度
    getSurroundingPoisByPoint(callBackFunc, lng?, lat?) {
        const result = {
            center:
                { lng: lng ? lng : this.locationObj.center.lng, lat: lat ? lat : this.locationObj.center.lat },
            name: this.locationObj.name, code: this.locationObj.code, address: '', location: {}
        };
        try {
            const geoc = new BMap.Geocoder();
            const pt = new BMap.Point(lng ? lng : this.locationObj.center.lng, lat ? lat : this.locationObj.center.lat);
            // add by andrew.wen 取当前定位中心经纬度画矩形ll1 左上角经纬度 ll4右下角经纬度
            geoc.getLocation(pt, rs => {
                let poisLen = rs.surroundingPois.length - 1;
                const poisDetail = rs.surroundingPois.length > 0 ? rs.surroundingPois[0].title : '';
                result.address = rs.address;
                // 返回同一个点则线上画矩形
                if (poisLen === 0) {
                    // tslint:disable-next-line:max-line-length
                    rs.surroundingPois[1] = { point: { lng: rs.surroundingPois[0].point.lng + 0.05, lat: rs.surroundingPois[0].point.lat + 0.05 } };
                    poisLen = 1;
                }
                const begainLargeThanEnd = rs.surroundingPois[0].point.lat > rs.surroundingPois[poisLen].point.lat;
                result.location = {
                    content: {
                        ll1: {
                            // tslint:disable-next-line:max-line-length
                            longitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lng : rs.surroundingPois[poisLen].point.lng,
                            // tslint:disable-next-line:max-line-length
                            latitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lat : rs.surroundingPois[poisLen].point.lat
                        },
                        ll2: {},
                        ll3: {},
                        ll4: {
                            // tslint:disable-next-line:max-line-length
                            longitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lng : rs.surroundingPois[0].point.lng,
                            // tslint:disable-next-line:max-line-length
                            latitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lat : rs.surroundingPois[0].point.lat
                        }
                    }
                };
                // 蜂喔用户1.9.18 店铺地址获取
                callBackFunc(result);
            });
        } catch (error) {
            console.log('error----->' + JSON.stringify(error));
            // this.setStore('mapPosition', result);
            callBackFunc(result);
        }
    }

    getCityIdByName(name) {
        let code = 4403;
        // tslint:disable-next-line:max-line-length
        const data = [{ i: 1101, n: "北京" }, { i: 6103, n: "宝鸡" }, { i: 5001, n: "重庆" }, { i: 5101, n: "成都" }, { i: 2201, n: "长春" }, { i: 4301, n: "长沙" }, { i: 3204, n: "常州" }, { i: 2102, n: "大连" }, { i: 4419, n: "东莞" }, { i: 4228, n: "恩施" }, { i: 4406, n: "佛山" }, { i: 3501, n: "福州" }, { i: 3607, n: "赣州" }, { i: 5201, n: "贵阳" }, { i: 4401, n: "广州" }, { i: 4503, n: "桂林" }, { i: 4413, n: "惠州" }, { i: 4601, n: "海口" }, { i: 2301, n: "哈尔滨" }, { i: 3301, n: "杭州" }, { i: 3401, n: "合肥" }, { i: 3604, n: "九江" }, { i: 3701, n: "济南" }, { i: 2202, n: "吉林" }, { i: 5301, n: "昆明" }, { i: 4103, n: "洛阳" }, { i: 4502, n: "柳州" }, { i: 3713, n: "临沂" }, { i: 6201, n: "兰州" }, { i: 5107, n: "绵阳" }, { i: 4409, n: "茂名" }, { i: 3201, n: "南京" }, { i: 4501, n: "南宁" }, { i: 3601, n: "南昌" }, { i: 3302, n: "宁波" }, { i: 3702, n: "青岛" }, { i: 3505, n: "泉州" }, { i: 3101, n: "上海" }, { i: 4112, n: "三门峡" }, { i: 4403, n: "深圳" }, { i: 1301, n: "石家庄" }, { i: 3205, n: "苏州" }, { i: 4602, n: "三亚" }, { i: 2101, n: "沈阳" }, { i: 1401, n: "太原" }, { i: 1201, n: "天津" }, { i: 4201, n: "武汉" }, { i: 3707, n: "潍坊" }, { i: 3303, n: "温州" }, { i: 3710, n: "威海" }, { i: 3402, n: "芜湖" }, { i: 3202, n: "无锡" }, { i: 6104, n: "咸阳" }, { i: 3203, n: "徐州" }, { i: 6101, n: "西安" }, { i: 3502, n: "厦门" }, { i: 4206, n: "襄阳" }, { i: 3706, n: "烟台" }, { i: 4205, n: "宜昌" }, { i: 4404, n: "珠海" }, { i: 4420, n: "中山" }, { i: 4302, n: "株洲" }, { i: 5203, n: "遵义" }, { i: 4101, n: "郑州" }];
        // tslint:disable-next-line:prefer-for-of
        for (let i = 0; i < data.length; i++) {
            if (data[i].n === name) {
                code = data[i].i;
                break;
            }
        }
        return code;
    }

    onlyRefreshCurrentPositionAndCallBack(callbackFunc) {
        const that = this;
        if (
            typeof (cordova) !== 'undefined'
            && typeof (cordova.plugins.baidumap_location) !== 'undefined') {
            cordova.plugins.baidumap_location.getCurrentPosition((res) => {
                let code: any;
                // 国际转换坐标百度坐标
                res = that.storageNewLocation(res);
                // 国际转换坐标百度坐标
                if (res.adCode) {
                    console.log('onlyRefreshCurrentPositionAndCallBack.getCurrentPosition...', res);
                    that.locationObj.districtCode = String(res.adCode);
                    code = String(res.adCode).substring(0, 4);
                    const cityName = String(res.city).replace("市", "");
                    const points = { lng: res.longitude, lat: res.latitude };
                    that.locationObj.center = points;
                    that.locationObj.code = String(code);
                    that.locationObj.name = cityName;
                    if (res.district) {
                        that.locationObj.district = res.district;
                    }
                    // 2.2.18 add locationDescribe
                    if (res.locationDescribe) {
                        that.locationObj.locationDescribe = res.locationDescribe;
                        that.appGlobalService.callBackFunctionOnGetAddressByPoint = res.locationDescribe;
                    }
                    // that.appGlobalService.getAddressLat = res.latitude;
                    // that.appGlobalService.getAddressLng = res.longitude;

                    // android 2.0用到 设备唯一标识
                    if (res.deviceUUID) {
                        that.setStore('deviceUUID', res.deviceUUID);
                    }

                    // android 2.0用到 设备型号
                    if (res.deviceModel) {
                        that.setStore('deviceModel', res.deviceModel);
                    }
                    that.setStore('currentCityPosition', that.locationObj);
                    that.setStore('position', that.locationObj);
                    that.setStore('mapPosition', that.locationObj);
                    that.setStore('askForTag', 0);
                    that.setStore('alreadyAllowPhysicalLocation', 'true');
                    that.setStore('alreadyGetCurrentLocation', 'true');
                    // 真实拿到定位数据才 callback
                    callbackFunc();
                } else {
                    if (res.longitude && res.latitude) {
                        console.log(JSON.stringify(res));
                        const geoc = new BMap.Geocoder();
                        const pt = new BMap.Point(res.longitude, res.latitude);
                        geoc.getLocation(pt, rs => {
                            try {
                                const points = { lng: res.longitude, lat: res.latitude };
                                that.locationObj.center = points;
                                that.locationObj.code = String(code);
                                that.locationObj.name = rs.addressComponents.city.replace('市', ''); //
                                that.locationObj.code = '' + this.getCityIdByName(that.locationObj.name);
                                if (rs.addressComponents.district) {
                                    that.locationObj.district = rs.addressComponents.district;
                                }
                                const poisDetail = rs.surroundingPois.length > 0 ? rs.surroundingPois[0].title : '';
                                if (rs.addressComponents.district) {
                                    that.locationObj.locationDescribe = rs.addressComponents.city + poisDetail;
                                }
                                that.appGlobalService.callBackFunctionOnGetAddressByPoint = poisDetail;
                                // that.appGlobalService.getAddressLat = res.latitude;
                                // that.appGlobalService.getAddressLng = res.longitude;
                                that.setStore('currentCityPosition', that.locationObj);
                                that.setStore('position', that.locationObj);
                                that.setStore('mapPosition', that.locationObj);
                                that.setStore('askForTag', 0);
                                that.setStore('alreadyAllowPhysicalLocation', 'false');
                                that.setStore('alreadyGetCurrentLocation', 'true');
                                // 真实拿到定位数据才 callback
                                callbackFunc();

                            } catch (error) {
                                console.log('msg----->get address error ' + JSON.stringify(error));
                            } finally {

                            }
                        });
                    } else {
                        // window.alert('定位不在国内');
                        // 定位不在国内
                        console.log('msg----->position out of china');
                        that.locationObj = {
                            center: { lng: 114.066112, lat: 22.548511 },
                            name: '深圳', code: '4403', district: '', districtCode: '440300', locationDescribe: ''
                        };
                        that.setStore('currentCityPosition', that.locationObj);
                        that.setStore('position', that.locationObj);
                        that.setStore('mapPosition', that.locationObj);
                        // 真实拿到定位数据才 callback
                        callbackFunc();
                    }
                }
            }, (err) => {
                if (err === 'show setting') {
                    // console.log('show setting');
                    that.pageModalService.showSettingLocation();
                } else {
                    console.log('Location failed beacuse we can not get any loc information! ', err);
                    // that.appGlobalService.showToast("请在设置中允许铺铺旺APP使用您的位置信息", 1000, "middle");

                }
                callbackFunc();
            });
        } else {

            that.locationObj = {
                center: { lng: 114.066112, lat: 22.548511 },
                name: '深圳', code: '4403', district: '', districtCode: '440304', locationDescribe: ''
            };
            if (this.appGlobalService.callBackFunctionOnGetAddressByPoint) {
                that.locationObj.locationDescribe = this.appGlobalService.callBackFunctionOnGetAddressByPoint;
            }
            that.setStore('currentCityPosition', that.locationObj);
            that.setStore('position', that.locationObj);
            that.setStore('mapPosition', that.locationObj);
            that.setStore('alreadyGetCurrentLocation', 'true');
            callbackFunc();
        }
    }



    storageNewLocation(res) {
        const lat = res.latitude;
        const lng = res.longitude;
        // console.log(lat + "||latitude" );
        // console.log(lng + "||longitude");
        // wgs84转百度坐标系
        let ssws = this.wgs84togcj02(lng, lat);
        ssws = this.gcj02tobd09(ssws[0], ssws[1]);
        // 解决定位偏移
        res.latitude = ssws[1] - 0.000160;
        res.longitude = ssws[0] - 0.000160;
        return res;
    }

    // 地图定位精确方法
      /**
       * WGS84转GCj02
       */
    wgs84togcj02(lng, lat) {
        // let x_PI = 3.14159265358979324 * 3000.0 / 180.0;
        const PI = 3.1415926535897932384626;
        const a = 6378245.0;
        const ee = 0.00669342162296594323;
        if (this.outOfChina(lng, lat)) {
          return [lng, lat];
        } else {
            let dlat = this.transformlat(lng - 105.0, lat - 35.0);
            let dlng = this.transformlng(lng - 105.0, lat - 35.0);
            const radlat = lat / 180.0 * PI;
            let magic = Math.sin(radlat);
            magic = 1 - ee * magic * magic;
            const sqrtmagic = Math.sqrt(magic);
            dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
            dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
            const mglat = lat + dlat;
            const mglng = lng + dlng;
            return [mglng, mglat];
        }
      }

      /**
       * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
       * 即谷歌、高德 转 百度
       */

     gcj02tobd09(lng, lat) {
        const xPI = 3.14159265358979324 * 3000.0 / 180.0;
        const PI = 3.1415926535897932384626;
        const a = 6378245.0;
        const ee = 0.00669342162296594323;
        const z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * xPI);
        const theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * xPI);
        const bdLng = z * Math.cos(theta) + 0.0065;
        const bdLat = z * Math.sin(theta) + 0.006;
        return [bdLng, bdLat];
    }

      transformlat(lng, lat) {
        let x_PI = 3.14159265358979324 * 3000.0 / 180.0;
        let PI = 3.1415926535897932384626;
        let a = 6378245.0;
        let ee = 0.00669342162296594323;
        let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
        return ret
      }

      transformlng(lng, lat) {
        const xPI = 3.14159265358979324 * 3000.0 / 180.0;
        const PI = 3.1415926535897932384626;
        const a = 6378245.0;
        const ee = 0.00669342162296594323;
        let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
      }
    /**
     * 判断是否在国内，不在国内则不做偏移
     */
    outOfChina(lng, lat) {
        return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
    }
}
